package com.borened.netty.util;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.buffer.Unpooled;

import java.nio.charset.StandardCharsets;

/**
 * @author chengcaihua
 * @description
 * @since 2023-11-13 17:20
 */
public class ByteBufUtil {

    public static ByteBuf allocator(byte[] byteArr) {
        ByteBuf byteBuf = Unpooled.wrappedBuffer(byteArr);
        return byteBuf;
    }

    public static ByteBuf readByteBuf(ByteBuf byteBuf) {
        // 创建用于读取的ByteBuf对象
        ByteBuf readBuf = ByteBufAllocator.DEFAULT.buffer(byteBuf.readableBytes());
        // 从byteBuf中读取数据到readBuf
        byteBuf.readBytes(readBuf);
        return readBuf;
    }
    public static byte[] readBytes(ByteBuf byteBuf) {
        byte[] result = new byte[byteBuf.readableBytes()];
        byteBuf.readBytes(result);
        return result;
    }

    public static String readString(ByteBuf byteBuf) {
        byte[] bytes = readBytes(byteBuf);
        return new String(bytes, StandardCharsets.UTF_8);
    }
}
